﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace ColemanDevelopment.Utilities.Parsers.Xml
{
    public static class XmlParser
    {

        public static IEnumerable<XmlData> ParseXml(string xml)
        {
            var data = XElement.Parse(xml);
            // returnData = null;
            IEnumerable<XmlData> xData = null;

            if (data.Elements().Count() > 0)
            {

                xData = data.Elements().Select(x => new XmlData()
                    {
                        ElementName = x.Name.LocalName,
                        Attributes = ConvertToAttributePair(x.Attributes()),
                        RootNode = GetRootName(x)
                    });
            }
            else
            {
                xData = data.Attributes().Select(x => new XmlData()
                {
                    RootNode = null,
                    ElementName = data.Name.LocalName,
                    Attributes = new List<AttributePair>() { new AttributePair() { Name = x.Name.LocalName, Value = x.Value } }

                });

            }

            return xData;
        }

        private static List<AttributePair> ConvertToAttributePair(IEnumerable<XAttribute> attributes)
        {
            return attributes.Select(p => new AttributePair()
            {
                Name = p.Name.LocalName,
                Value = p.Value
            }).ToList();

        }

        private static string GetRootName(XElement element)
        {
            string name = null;
            XNode node = element.Nodes().FirstOrDefault();
            name = node == null ? null : node.Parent.Name.LocalName;

            return name;
        }

    }
}
